package com.demo.web.security;


import com.demo.model.Role.Role;
import com.demo.model.SysUser.SysUser;
import com.demo.service.User.SysUserservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

//自定义UserDetailsService
@Service
public class MyUserDetailServicelmpl implements UserDetailsService {
    @Autowired
    private SysUserservice sysUserservice;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser=sysUserservice.getUserOneByName(username);
        if(sysUser==null){
            throw new UsernameNotFoundException("用户不存在");
        } else if (sysUser.getIsDel()==1) {
            throw new UsernameNotFoundException("当前用户被删除");
        } else if (sysUser.getDisabled()==1) {
            throw new UsernameNotFoundException("该账户被禁用");
        }

        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        List<Role> roleList=sysUserservice.getRolesByUid(sysUser.getUid());
        for (Role role:roleList
        ) {
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        }

        return new User(sysUser.getUsername(),sysUser.getPassword(),grantedAuthorities);
    }


}
